package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.AttendanceTwoJdbc;
import com.wuseguang.springcloud.service.AttendanceTwoService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @描述
 * @创建人 zm
 * @创建时间 2020/8/6 10:22
 */
@Service
public class AttendanceTwoServiceImpl implements AttendanceTwoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AttendanceTwoJdbc attendanceJdbc;


    @Autowired
    private WXJdbc wXJdbc;


    //考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤 9未打卡
    private static Integer zhengchang = 1;//正常打卡

    private static Integer chidao = 2;//迟到

    private static Integer zaotui = 5;//早退

    /**
     * @描述 查询该考勤组该段人员所有考勤状态
     * @创建人 zm
     * @创建时间 2020/2/20
     */
    @Override
    public Result queryAttendUserStatusList(String deviceid, Integer groupid, Integer grouptype, Integer shiftid, String time) {
        try {
            Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
            if (stringObjectMap == null) {
                return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
            }
            Map<String, Object> maps = new HashMap<>();
            String gettime = DateUtil.gettime();
            String time1 = DateUtil.time();
            Map<String, Object> map = null;
            String attendType = "";//0 固定考勤  1 活动考勤
            if (!StringUtils.isEmpty(groupid) && groupid != 0) {//有考勤组id  直接或班次信息
                String sql1 = "SELECT name,attend_group_type FROM attend_group WHERE id=? ";
                Map<String, Object> mapType = attendanceJdbc.queryMap(sql1, groupid);
                maps.put("name", mapType.get("name").toString());
                maps.put("groupid", groupid);
                maps.put("shiftid", shiftid);
                maps.put("grouptype", grouptype);
                attendType = mapType.get("attend_group_type").toString();
                //查询班次详情
                String sql = "SELECT  type,starttime_one starttime,endtime_one endtime,starttime_two starttime1,endtime_two endtime1,s_ejecttime_one s_ejecttime,e_ejecttime_one e_ejecttime,s_ejecttime_two  s_ejecttime1,e_ejecttime_two  e_ejecttime1,school_id FROM attend_shift WHERE id=? ";
                try {
                    map = attendanceJdbc.queryMap(sql, shiftid);
                } catch (Exception e) {
                    logger.info("queryAttendUserStatusAll-->mapList,error={}", e);
                }
            } else {//考勤页面手动打开，自行判断考勤内容
                //情况一 当天考勤 次日生效
                String sql = "  SELECT g.shift_id  , g.id , g.name ,g.attend_type grouptype ,g.attend_group_type,f.id shiftid,f.type,f.starttime_one starttime,f.endtime_one endtime,f.starttime_two starttime1,f.endtime_two endtime1 " +
                        " ,f.s_ejecttime_one  s_ejecttime,f.e_ejecttime_one e_ejecttime,f.s_ejecttime_two s_ejecttime1,f.e_ejecttime_two e_ejecttime1,f.school_id FROM  " +
                        "     attend_group g,class_attend_group s,attend_shift f WHERE s.class_id=? AND g.id=s.attend_group_id AND f.id=g.shift_id  ORDER BY f.starttime_one  LIMIT 1 ";
                try {
                    map = attendanceJdbc.queryMap(sql, stringObjectMap.get("classid"));
                } catch (Exception e) {
                    logger.info("queryAttendUserStatusAll-->erorr={}", e);
                }

                if (map != null) {
                    maps.put("name", map.get("name"));
                    maps.put("groupid", map.get("id"));
                    maps.put("shiftid", map.get("shift_id"));
                    maps.put("grouptype", map.get("grouptype"));
                    attendType = map.get("attend_group_type").toString();
                } else {

                    //情况二 当天考勤  当天生效
                    sql = " SELECT  g.shift_id , g.id , g.name ,g.attend_type grouptype ,g.attend_group_type,f.id shiftid,f.type,f.starttime_one starttime,f.endtime_one endtime,f.starttime_two starttime1,f.endtime_two endtime1 ,f.s_ejecttime_one  s_ejecttime,f.e_ejecttime_one e_ejecttime,f.s_ejecttime_two s_ejecttime1,f.e_ejecttime_two e_ejecttime1,f.school_id FROM   attend_group g,class_attend_group s,attend_shift f,attend_group_shift t WHERE s.class_id=? AND g.id=s.attend_group_id  AND t.shift_id=f.id AND t.attend_group_id=g.id  AND t.sort=? ORDER BY f.starttime_one  limit 1";
                    try {
                        map = attendanceJdbc.queryMap(sql, stringObjectMap.get("classid"), DateUtil.getWeeksInt(gettime));
                    } catch (Exception e) {
                        logger.info("queryAttendUserStatusAll-->erorr={}", e);
                    }

                    if (map == null || "-1".equals(map.get("shift_id").toString())) {//当天为休息
                        return new Result();
                    }
                    maps.put("name", map.get("name"));
                    maps.put("groupid", map.get("id"));
                    maps.put("shiftid", map.get("shiftid"));
                    maps.put("grouptype", map.get("grouptype"));
                    attendType = map.get("attend_group_type").toString();
                }
            }


            if (map != null) {
                if (StringUtils.isEmpty(groupid) || groupid == 0) {//重新赋值
                    groupid = (int) map.get("id");
                    grouptype = (int) map.get("grouptype");
                    shiftid = (int) map.get("shiftid");
                }
                int a = 0;
                int type = (int) map.get("type");//考勤类型:0 1天1次、1 1天2次
                String s_ejecttime = map.get("s_ejecttime") == null ? "" : (String) map.get("s_ejecttime");//第一段进班弹出dialog 时间
                String e_ejecttime = map.get("e_ejecttime") == null ? "" : (String) map.get("e_ejecttime");//第一段离班弹出dialog 时间
                String s_ejecttime1 = map.get("s_ejecttime1") == null ? "" : (String) map.get("s_ejecttime1");//第二段进班弹出dialog 时间
                String e_ejecttime1 = map.get("e_ejecttime1") == null ? "" : (String) map.get("e_ejecttime1");//第二段离班弹出dialog 时间
                String starttime = map.get("starttime") == null ? "" : (String) map.get("starttime");//第一段进班时间
                String endtime = map.get("endtime") == null ? "" : (String) map.get("endtime");//第一段离班时间
                String starttime1 = map.get("starttime1") == null ? "" : (String) map.get("starttime1");//第二段进班时间
                String endtime1 = map.get("endtime1") == null ? "" : (String) map.get("endtime1");//第二段离班时间
                starttime = DateUtil.AddTime(gettime, starttime);
                endtime = DateUtil.AddTime(gettime, endtime);
                starttime1 = DateUtil.AddTime(gettime, starttime1);
                endtime1 = DateUtil.AddTime(gettime, endtime1);
                String s = "";
                String s1 = "";
                String s2 = "";
                String s3 = "";
                if (type == 0) {
                    if (!StringUtils.isEmpty(endtime) && !StringUtils.isEmpty(starttime1)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                        long l = DateUtil.getcompTime(starttime1, endtime);
                        s = DateUtil.addtimeMinutes(endtime, (int) l / 2);
                    } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                        long l = DateUtil.getcompTime(endtime1, starttime);
                        s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                    }
                } else {
                    logger.info("一天两段,starttime={},endtime={},starttime1={},endtime1={}", starttime, endtime, starttime1, endtime1);
                    //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                    long l = DateUtil.getcompTime(endtime, starttime);
                    s2 = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                    //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 第一段离班正常和第二段的进班正常
                    long l1 = DateUtil.getcompTime(starttime1, endtime);
                    s1 = DateUtil.addtimeMinutes(endtime, (int) l1 / 2);
                    //求第二段考勤的中间时间  用来区分 第二段进班迟到和离班早退
                    long l2 = DateUtil.getcompTime(endtime1, starttime1);
                    s3 = DateUtil.addtimeMinutes(starttime1, (int) l2 / 2);
                }
                logger.info("time={}", time);
                if ((!StringUtils.isEmpty(time) && time.equals(s_ejecttime)) || (type == 0 && DateUtil.getcompTime(time1, s) <= 0) || (type == 1 && DateUtil.getcompTime(time1, s2) <= 0)) {//为第一段进班考勤
                    maps.put("attendtime", new StringBuilder("进班考勤: ").append(starttime).toString());
                    maps.put("time", starttime);
                    a = 1;
                }
                if ((!StringUtils.isEmpty(time) && time.equals(e_ejecttime)) || (type == 1 && DateUtil.getcompTime(time1, s2) > 0 && DateUtil.getcompTime(time1, s1) <= 0)) {//为第一段离班考勤
                    maps.put("attendtime", new StringBuilder("离班考勤: ").append(endtime).toString());
                    maps.put("time", endtime);
                    a = 2;
                }

                if ((!StringUtils.isEmpty(time) && time.equals(s_ejecttime1)) || (type == 1 && DateUtil.getcompTime(time1, s1) > 0 && DateUtil.getcompTime(time1, s3) <= 0)) {//为第二段进班考勤
                    maps.put("attendtime", new StringBuilder("进班考勤: ").append(starttime1).toString());
                    maps.put("time", starttime1);
                    a = 3;
                }

                if ((!StringUtils.isEmpty(time) && time.equals(e_ejecttime1)) || (type == 0 && DateUtil.getcompTime(time1, s) > 0) || (type == 1 && DateUtil.getcompTime(time1, s3) > 0)) {//为第二段离班考勤
                    maps.put("attendtime", new StringBuilder("离班考勤: ").append(endtime1).toString());
                    maps.put("time", endtime1);
                    a = 4;
                }
                logger.info("Attend-2.0V,queryAttendUserStatusAllStatus,status={}", a);
                Map<String, Object> list = queryAttendUserStatus(starttime, endtime, starttime1, endtime1, type, a, grouptype, groupid, shiftid, s, s1, s2, s3, attendType, stringObjectMap.get("classid").toString());
                maps.putAll(list);
            }
            logger.info("Attend,queryAttendUserStatusAll-->maps={}", maps.toString());
            if (maps != null && maps.size() > 0) {
                maps.put("datetime", new StringBuilder(gettime).append(" ").append(DateUtil.getWeeks(gettime)).toString());
                return new Result(maps);
            }
            return new Result();
        } catch (Exception e) {
            logger.info("queryAttendUserStatusAll-->erorr={}", e);
        }
        return new Result();
    }


    /**
     * 考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤 9未打卡
     *
     * @创建人 zm
     * @创建时间 2020/2/21
     */
    public Map<String, Object> queryAttendUserStatus(String starttime, String endtime, String starttime1, String endtime1, int type, int a, Integer grouptype, Integer groupid, Integer shiftid, String s, String s1, String s2, String s3, String attendType, String classid) {
        String sql = "";
        String sql1 = "";
        String gettime = DateUtil.gettime();
        int param4 = 0;//返回类型
        int param = 0;//返回类型
        String param1 = "";//考勤时间
        String param2 = "";//开始时间
        String param3 = "";//结束时间
        if (type == 0) {//一天一段考勤
            logger.info("一天一段，s={}", s);
            if (a == 1) {
                param = chidao;
                param1 = starttime;
                param2 = DateUtil.addDays(gettime, -1);
                param3 = s;
                param4 = zhengchang;
            }
            if (a == 4) {
                param = zhengchang;
                param1 = endtime1;
                param2 = s;
                param3 = DateUtil.addDays(gettime, 1);
                param4 = zaotui;
            }
        } else {//一天两段考勤
            logger.info("一天两段，s={}，s1={}，s3={}", s, s1, s3);
            if (a == 1) {
                param = chidao;
                param1 = starttime;
                param2 = DateUtil.addDays(gettime, -1);
                param3 = s2;
                param4 = zhengchang;
            }
            if (a == 2) {
                param = zhengchang;
                param1 = endtime;
                param2 = s2;
                param3 = s1;
                param4 = chidao;
            }
            if (a == 3) {
                param = chidao;
                param1 = starttime1;
                param2 = s1;
                param3 = s3;
                param4 = zhengchang;
            }
            if (a == 4) {
                param = zhengchang;
                param1 = endtime1;
                param2 = s3;
                param3 = DateUtil.addDays(gettime, 1);
                param4 = zaotui;
            }
        }
        if ("0".equals(attendType)) {
            sql = " SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,IF((SELECT  COUNT(1) FROM  vacation WHERE student_id=t.id AND state=2 AND DATE(stime)<=DATE(NOW()) AND DATE(etime)>= DATE(NOW()))>0,0,(CASE WHEN  a.attendtime IS NULL THEN 9 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  )) attendtype FROM  attend_group_user u,student t LEFT JOIN " +
                    "  class_attendlist a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "   TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.class_id=" + classid + " AND t.id=u.userid GROUP BY t.id order by a.attendtime desc";

            sql1 = "SELECT  COUNT(1) ycount,SUM(IF(attendtype = 1 OR attendtype = 2 OR attendtype = 4 OR attendtype = 5 , 1, 0))  scount,SUM(IF(attendtype = 9, 1, 0)) wcount FROM " +
                    "( SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,(CASE WHEN  a.attendtime IS NULL THEN 9 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  ) attendtype FROM  attend_group_user u,student t LEFT JOIN " +
                    "  class_attendlist a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "   TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.class_id=" + classid + " AND t.id=u.userid GROUP BY t.id  order by a.attendtime desc ) s ";
        } else {
            sql = " SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,IF((SELECT  COUNT(1) FROM  vacation WHERE student_id=t.id AND state=2 AND DATE(stime)<=DATE(NOW()) AND DATE(etime)>= DATE(NOW()))>0,0,(CASE WHEN  a.attendtime IS NULL THEN 9 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  )) attendtype FROM  attend_group_user u,student t LEFT JOIN " +
                    "  class_attendlist a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "   TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id order by a.attendtime desc";

            sql1 = "SELECT  COUNT(1) ycount,SUM(IF(attendtype = 1 OR attendtype = 2 OR attendtype = 4 OR attendtype = 5 , 1, 0))  scount,SUM(IF(attendtype = 9, 1, 0)) wcount FROM " +
                    "( SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,(CASE WHEN  a.attendtime IS NULL THEN 9 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  ) attendtype FROM  attend_group_user u,student t LEFT JOIN " +
                    "  class_attendlist a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "   TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id  order by a.attendtime desc ) s ";
        }

        List<Map<String, Object>> mapList = null;//查询考勤组人员今天所有考勤信息
        Map<String, Object> map = null;
        try {
            mapList = attendanceJdbc.queryListMap(sql, param1, param4, param, groupid, param2, param3, groupid);
            map = attendanceJdbc.queryMap(sql1, param1, param4, param, groupid, param2, param3, groupid);
        } catch (Exception e) {
            logger.info("queryAttendUserStatus-->mapList,error={}", e);
        }
        map.put("attendlist", mapList);
        return map;
    }

    /**
     * @描述 查询对应班牌所有考勤dialog时间
     * @创建人 zm
     * @创建时间 2020/8/6
     */
    @Override
    public Map<String, Object> queryAttendGroupDialog(String deviceid) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object classid = stringObjectMap.get("classid");

        String sql = " UPDATE bancard SET dialogflag=1 WHERE deviceid=?";
        attendanceJdbc.updateByParameter(sql, deviceid);

        //查询这个班级班牌里面所有考勤组（目前只支持 一个班级对应一个考勤组）
        sql = "SELECT g.id groupid,g.name groupname,g.shift_id,g.attend_type grouptype FROM attend_group g,class_attend_group d,classes s WHERE s.id=?  AND d.attend_group_id=g.id AND d.class_id=s.id LIMIT 1";
        Map<String, Object> groupMap = null;
        try {
            groupMap = attendanceJdbc.queryMap(sql, classid);
        } catch (Exception e) {
            logger.info("queryBanAttendGroup2.0V,error={}", e);
        }
        if (groupMap != null) {
            sql = "SELECT  shift_id,sort FROM attend_group_shift WHERE attend_group_id=? ORDER BY sort";
            List<Map<String, Object>> maps = attendanceJdbc.queryListMap(sql, groupMap.get("groupid"));
            sql = "SELECT  shift_id  string FROM attend_group WHERE id=? ";
            String groupid = attendanceJdbc.queryString(sql, groupMap.get("groupid"));
            int weeksInt = DateUtil.getWeeksInt(DateUtil.gettime());
            sql = " SELECT  id,name,type,starttime_one starttime,endtime_one endtime,starttime_two starttime1,endtime_two endtime1,s_ejecttime_one s_ejecttime,e_ejecttime_one e_ejecttime,s_ejecttime_two s_ejecttime1,e_ejecttime_two e_ejecttime1,school_id FROM attend_shift WHERE  id=? ";
            Map<String, Object> mapShift = null;
            for (int i = 0; i < maps.size(); i++) {//遍历所有班次
                Map<String, Object> map = maps.get(i);
                String weeks = getWeeks(i);
                if (i == weeksInt && !"0".equals(groupid)) {//当天班次为 次日生效 特殊处理
                    try {
                        mapShift = attendanceJdbc.queryMap(sql, groupid);
                    } catch (Exception e) {
                        logger.info("queryBanAttendGroupAll-2.0V,error={}", e);
                    }
                    groupMap.putAll(groupMap(mapShift, weeks));
                } else {
                    if ("0".equals(map.get("shift_id").toString())) {//休息
                        groupMap.put(weeks, null);
                    } else {
                        try {//查询班次信息
                            mapShift = attendanceJdbc.queryMap(sql, map.get("shift_id"));
                        } catch (Exception e) {
                            logger.info("queryBanAttendGroupAll-2.0V,error={}", e);
                        }
                        groupMap.putAll(groupMap(mapShift, weeks));
                    }
                }
            }
        }
        return groupMap;
    }


    /**
     * @描述 班牌人脸考勤 添加考勤
     * @创建人 zm
     * @创建时间 2020/2/22
     */
    @Transactional
    @Override
    public Result addAttendStudent(String deviceid, Integer userid, Integer groupid, Integer grouptype, Integer shiftid, String time) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        String sql3 = "SELECT attend_group_type string  FROM attend_group WHERE id=? ";
        String s2 = attendanceJdbc.queryString(sql3, groupid);

        Map<String, Object> map1 = null;
        Map<String, Object> studentMap = null;
        try {
            String  sql = " SELECT  student_name studentName FROM student WHERE id=?";
            studentMap = attendanceJdbc.queryMap(sql, userid);
            sql = "SELECT s.id,s.class_id classid,s.student_name FROM attend_group_user u ,student s WHERE u.userid=s.id AND attend_group_id=? AND s.id=? ";
            if ("0".equals(s2)) {
                sql += " AND s.class_id=" + stringObjectMap.get("classid");
            }

            sql += " LIMIT 1";
            map1 = attendanceJdbc.queryMap(sql, groupid, userid);
        } catch (Exception e) {

        }

        if (studentMap == null) {
            return new Result(CodeUtil.NOTAN_ATTENDANCEPERSON.getCode(), "该学生不存在！");
        }

        if (map1 == null && "0".equals(s2)) {
            return new Result(CodeUtil.NOTAN_ATTENDANCEPERSON, studentMap);
        }
        if (map1 == null) {
            return new Result(CodeUtil.NOTAN_ATTENDANCEPERSON, studentMap);
        }
        Object school_id = stringObjectMap.get("school_id");
        //查询班次详情
        String sql = "SELECT  type,starttime_one starttime,endtime_one endtime,starttime_two starttime1,endtime_two endtime1,s_ejecttime_one s_ejecttime,e_ejecttime_one e_ejecttime,s_ejecttime_two s_ejecttime1,e_ejecttime_two e_ejecttime1,school_id  FROM attend_shift WHERE id=? ";
        Map<String, Object> map = null;
        try {
            map = attendanceJdbc.queryMap(sql, shiftid);
        } catch (Exception e) {
            logger.info("addAttend-->mapList,error={}", e);
        }
        if (map != null) {
            String gettime = DateUtil.gettime();
            String param = "";//开始时间
            String param1 = "";//结束时间
            int type = (int) map.get("type");//考勤类型:0 1天1次、1 1天2次
            String starttime = map.get("starttime") == null ? "" : (String) map.get("starttime");//第一段进班时间
            String endtime = map.get("endtime") == null ? "" : (String) map.get("endtime");//第一段离班时间
            String starttime1 = map.get("starttime1") == null ? "" : (String) map.get("starttime1");//第二段进班时间
            String endtime1 = map.get("endtime1") == null ? "" : (String) map.get("endtime1");//第二段离班时间
            starttime = DateUtil.AddTime(gettime, starttime);
            endtime = DateUtil.AddTime(gettime, endtime);
            starttime1 = DateUtil.AddTime(gettime, starttime1);
            endtime1 = DateUtil.AddTime(gettime, endtime1);//
            int attendtype = 2;
            if (type == 0) {//一天一段考勤
                String s = "";
                if (!StringUtils.isEmpty(endtime) && !StringUtils.isEmpty(starttime1)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                    long l = DateUtil.getcompTime(starttime1, endtime);
                    s = DateUtil.addtimeMinutes(endtime, (int) l / 2);
                } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                    long l = DateUtil.getcompTime(endtime1, starttime);
                    s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                }
                if (time.equals(starttime)) {//为第一段进班考勤
                    param = gettime;
                    param1 = s;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime) > 0) {
                        attendtype = 3;
                    }
                }
                if (time.equals(endtime1)) {//为第一段离班考勤
                    attendtype = 9;
                    param = s;
                    param1 = DateUtil.addDays(gettime, 1);
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime1) < 0) {
                        attendtype = 6;
                    }
                }
            } else {//一天两段考勤
                logger.info("一天两段,starttime={},endtime={},starttime1={},endtime1={}", starttime, endtime, starttime1, endtime1);
                //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                long l = DateUtil.getcompTime(endtime, starttime);
                String s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 第一段离班正常和第二段的进班正常
                long l1 = DateUtil.getcompTime(starttime1, endtime);
                String s1 = DateUtil.addtimeMinutes(endtime, (int) l1 / 2);
                //求第二段考勤的中间时间  用来区分 第二段进班迟到和离班早退
                long l2 = DateUtil.getcompTime(endtime1, starttime1);
                String s3 = DateUtil.addtimeMinutes(starttime1, (int) l2 / 2);
                logger.info("一天两段，s={}，s1={}，s3={}", s, s1, s3);
                if (time.equals(starttime)) {//为第一段进班考勤
                    param = gettime;
                    param1 = s;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime) > 0) {
                        attendtype = 3;
                    }
                }
                if (time.equals(endtime)) {//为第一段离班考勤
                    attendtype = 9;
                    param = s;
                    param1 = s1;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime) < 0) {
                        attendtype = 6;
                    }
                }

                if (time.equals(starttime1)) {//为第二段进班考勤
                    param = s1;
                    param1 = s3;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime1) > 0) {
                        attendtype = 3;
                    }
                }

                if (time.equals(endtime1)) {//为第二段离班考勤
                    attendtype = 9;
                    param = s3;
                    param1 = DateUtil.addDays(gettime, 1);
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime1) < 0) {
                        attendtype = 6;
                    }
                }
            }
            String sql1 = " SELECT COUNT(*) count FROM class_attendlist WHERE attend_group_id=? AND shift_id=? AND school_id=? " +
                    " AND userid=?  AND attendtime>=? AND attendtime<=?";
            logger.info("groupid={}, shiftid={}, school_id={}, userid={}, param={}, param1={}", groupid, shiftid, school_id, userid, param, param1);
            Integer integer = attendanceJdbc.queryCount(sql1, groupid, shiftid, school_id, userid, param, param1);
            String sql2 = "insert into `class_attendlist` (`userid`, `attend_group_id`, `shift_id`,  `school_id`, `attendtime`, `opertime`)" +
                    " values(?,?,?,?,now(),now())";
            if (integer == 0) {
                int i = attendanceJdbc.updateByParameter(sql2, userid, groupid, shiftid, school_id);
                if (i > 0) {

                    addAttendanceNotice(userid, groupid, attendtype, map1);

//                    HashMap<String, Object> stringIntegerHashMap = new HashMap<>();
//                    stringIntegerHashMap.put("attendtype", attendtype);
//                    //推送考勤信息
//                    //小程序推送
//                    //attendPush(userid, attendtype);
//                    //公众号推送
//                    //officialAccountPush(userid, attendtype);
//                    stringIntegerHashMap.put("studentName", map1.get("student_name"));
//                    return new Result(stringIntegerHashMap);
                    return new Result(studentMap);
                }
                return new Result(CodeUtil.ATTENDANCE_FAILURE, studentMap);
            }
//            HashMap<String, Object> stringIntegerHashMap = new HashMap<>();
//            stringIntegerHashMap.put("attendtype", attendtype);
//            //推送考勤信息
//            //小程序推送
//            //attendPush(userid, attendtype);
//            //公众号推送
//            //officialAccountPush(userid, attendtype);
//            stringIntegerHashMap.put("studentName", map1.get("student_name"));
            return new Result(CodeUtil.REPEAT_ATTENDANCE, studentMap);
        }
        return new Result(CodeUtil.ATTENDANCE_FAILURE, studentMap);
    }

    /**
     * @描述 添加 考勤通知
     * 对考勤做出判断  考勤类型: 0 病假 1事假 2 正常 3 进班迟到 4进班缺卡 5 离班缺卡 6 离班早退 7 缺勤 8 未打卡 9离班正常
     * @创建人 zm
     * @创建时间 2020/3/1
     */
    public void addAttendanceNotice(Integer userid, Integer groupid, int attendtype, Map<String, Object> map) {
        String sql = "insert into `attendance_notice`(`student_id`,`class_id`,`attend_group_id`,`attendtype`,`opertime`) " +
                "values(?,?,?,?,now())";
        attendanceJdbc.updateByParameter(sql, userid, map.get("classid"), groupid, attendtype);
    }


    /**
     * 把学生的考勤推送家长 公众号
     *
     * @param studentId  学生id
     * @param attendtype 考勤类型 2 进班正常 3 进班迟到  6 离班早退 9 离班正常
     */
    public void officialAccountPush(Integer studentId, Integer attendtype) {

        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";
        //家长openid
        Map<String, Object> parent = attendanceJdbc.queryMap(sql, studentId);
        //家长的openId
        String openId = (String) parent.get("open_id_two");

        //判断openId是否为空
        if (!StringUtils.isEmpty(openId)) {


            //查询学生名字
            sql = "select student_name string from student where id = ?";
            String studenName = attendanceJdbc.queryString(sql, studentId);
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first", "家长您好，您的孩子有一条新的考勤信息。");
            pushMap.put("keyword1", studenName);
            pushMap.put("keyword2", DateUtil.time());
            pushMap.put("keyword3", getAttendtype(attendtype));
            pushMap.put("remark", "感谢您的支持。");

            //跳转小程序信息
            JSONObject appletJson = new JSONObject();
            appletJson.put("appid", "wx30b606bac7775eba");
            appletJson.put("pagepath", "pages/attendance/index");

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken, openId, "31YxmArTVzKpLSYIJ5EmH2PR35mMNfu96_VLOlTebBE", "", appletJson, json);

        }
    }

    /**
     * 获取类型
     *
     * @param attendtype 2 正常 3 进班迟到  6 离班早退 9 离班正常
     * @return
     */
    public String getAttendtype(Integer attendtype) {
        if (attendtype == 2) {
            return "进班正常";
        } else if (attendtype == 3) {
            return "进班迟到";
        } else if (attendtype == 6) {
            return "离班早退";
        } else if (attendtype == 9) {
            return "离班正常";
        } else {
            return "正常";
        }
    }


    public Map<String, Object> groupMap(Map<String, Object> map, String weeks) {
        Map<String, Object> groupMap = new HashMap<>();
        if (map != null) {
            if ((int) map.get("type") == 0) {//一天一次考勤
                Map<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("id", map.get("id"));//班次id
                stringObjectHashMap.put("starttime", map.get("starttime"));
                stringObjectHashMap.put("endtime", map.get("endtime1"));
                stringObjectHashMap.put("s_ejecttime", map.get("s_ejecttime"));
                stringObjectHashMap.put("e_ejecttime", map.get("e_ejecttime1"));
                groupMap.put(weeks, stringObjectHashMap);
            } else {
                groupMap.put(weeks, map);
            }
        } else {
            groupMap.put(weeks, null);
        }
        return groupMap;
    }


    public String getWeeks(int s) {
        String week = "";
        if (s == 0) {
            week = "monday";
        } else if (s == 1) {
            week = "tuesday";
        } else if (s == 2) {
            week = "wednesday";
        } else if (s == 3) {
            week = "thursday";
        } else if (s == 4) {
            week = "friday";
        } else if (s == 5) {
            week = "saturday";
        } else if (s == 6) {
            week = "sunday";
        }
        return week;
    }

}
